package disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

import java.util.concurrent.Executors;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-12-20 19:51
 **/
public class DisruptorTest01 {


    public static void main(String[] args) {

        /**
         *  Disruptor 构建了一个环形数组
         *  这个数组首尾相连，
         *  在初始化的时候，通过 event 工厂，按照数组长度创建全部  event 对象，
         *  当数组中的对象需要变化时， 直接改变对象中的值（覆盖），不需要重新创建
         *
         */

        // The factory for the event 创建event 的工厂
        DisruptorEventFactory disruptorEventFactory = new DisruptorEventFactory();
        // Specify the size of the ring buffer, must be power of 2.
        // 数组长度，一定是2的幂次方
        int bufferSize = 1024;
        // Construct the Disruptor 创建
        Disruptor<DisruptorEvent> disruptor = new Disruptor<>(disruptorEventFactory, bufferSize, Executors.defaultThreadFactory());
        // Connect the handler 指定处理程序
        disruptor.handleEventsWith(new DisruptorEventHandler(1));
        // Start the Disruptor, starts all threads running
        // 启动程序，起开所有线程
        disruptor.start();
        // Get the ring buffer from the Disruptor to be used for publishing.
        // 从Disruptor获取用于发布的环形缓冲区。
        RingBuffer<DisruptorEvent> ringBuffer = disruptor.getRingBuffer();

        // 官方示例
        // Grab the next sequence 获取下一索引位置
        long sequence = ringBuffer.next();
        try {
            // Get the entry in the Disruptor 根据索引位置获取对象
            DisruptorEvent event = ringBuffer.get(sequence);
            // Fill with data 填充数据
            event.set(8888L);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ringBuffer.publish(sequence);
            disruptor.shutdown();
        }

    }
}
